package com.shujia.scala

import scala.io.Source

object Demo33Student {
  def main(args: Array[String]): Unit = {

    /**
      * 1、统计总分年级排名前十学生各科的分数
      * 1、计算学生的总分
      * 2、按照总分排序，取前十
      * 3、取出这部分学生各科的分数
      *
      */

    //1、读取文件
    val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList


    //2、将数据进行拆分
    val kvScores: List[(String, String, Int)] = scores
      //按照逗号分割数据
      .map(line => line.split(","))
      //过滤脏数据
      .filter(arr => arr.length == 3)
      .map {
        //匹配数据，取出字段
        case Array(id: String, cId: String, sco: String) =>
          (id, cId, sco.toInt)
      }


    //3、按照学号分组
    val groupBySco: Map[String, List[(String, String, Int)]] = kvScores.groupBy {
      case (id: String, _: String, _: Int) => id
    }

    //4、计算学生的总分

    val sumSco: Map[String, Int] = groupBySco.map {
      case (id: String, scos: List[(String, String, Int)]) =>

        val sumSco: Int = scos
          .map {
            //取出分数
            case (_: String, _: String, sco: Int) => sco
          }
          //计算总分
          .sum

        //返回数据
        (id, sumSco)
    }

    //转换成list集合才能排序
    val sumScoList: List[(String, Int)] = sumSco.toList

    //按照总分降序排序
    val sortSumSco: List[(String, Int)] = sumScoList.sortBy {
      case (_: String, sumSco: Int) => -sumSco
    }

    //取出总分排名前十的学生
    val top10: List[(String, Int)] = sortSumSco.take(10)

    //取出前十学生学号
    val ids: List[String] = top10.map(kv => kv._1)


    //获取这部分学生各科的分数
    val top10Scores: List[(String, String, Int)] = kvScores.filter {
      case (id: String, _: String, _: Int) =>
        ids.contains(id)
    }


    top10Scores.foreach(println)

  }

}
